<template>
  <div class="similar-question-item">
    <div class="title">
      <p class="left">
        <span class="num">{{ props.index }}</span>
        <span>{{ getType || '题目类型' }}</span>
        <span>{{ getDifficulty || '题目难度' }}</span>
      </p>
      <p class="right">
        <!-- <label>校本题库</label> -->
      </p>
    </div>
    <div ref="questionRef" class="question">
      <RbQuestion :questionData="questionData" :option="rbqOption"></RbQuestion>
    </div>
    <div class="footer">
      <button
        @click="showAnswer()"
        class="btn-text answer-btn"
        :class="{ active: props.isShowAnswer }"
      >
        <span class="icon"></span>答案解析
      </button>
      <button
        @click="check()"
        class="btn-primary select-btn"
        :class="{ active: props.isChecked }"
      >
        {{ props.isChecked ? '已选' : '选入' }}
      </button>
    </div>
    <ul v-if="props.isShowAnswer" class="answer">
      <li class="answer-item">
        <label>正确答案：</label>
        <!-- 单选/多选 -->
        <template v-if="props.content.type === 1 || props.content.type === 2">
          <p class="detail" v-html="getAnswer || '略'"></p>
        </template>
        <!-- 判断题 -->
        <template v-else-if="props.content.type === 36">
          <p class="detail">
            {{ Number(props.content.correct_answer) === 0 ? '正确' : '错误' }}
          </p>
        </template>
        <template v-else>
          <div
            class="detail"
            v-if="
              getParseRes.subQuestions && getParseRes.subQuestions.length > 0
            "
          >
            <p
              v-for="(item, index) in getParseRes.subQuestions"
              v-html="item.answer"
              :key="index"
            ></p>
          </div>
          <p class="detail" v-else v-html="getParseRes.answer || '略'"></p>
        </template>
      </li>
      <li>
        <label>解析：</label>
        <div
          class="detail"
          v-if="getParseRes.subQuestions && getParseRes.subQuestions.length > 0"
        >
          <p
            v-for="(item, index) in getParseRes.subQuestions"
            v-html="item.solution"
            :key="index"
          ></p>
        </div>
        <p v-else class="detail" v-html="getParseRes.solution || '略'"></p>
      </li>
      <li>
        <label class="key-point-label">知识点：</label>
        <p class="detail key-point-list">
          <span
            v-for="(item, index) in props.content.keypoint"
            :key="index"
            class="key-point"
          >
            {{ item.name }}
          </span>
        </p>
      </li>
      <li v-if="videoUrl.url">
        <label class="explain-label">微课讲解：</label
        ><button class="explain" @click="showVideo">
          原题讲解<label></label>
        </button>
      </li>
    </ul>
  </div>
</template>
<script setup>
import { DIFFICULTY_ENUM, letters } from '../constant'
import RbQuestion from '@ebag/rb-question-vue3'
import QuestionParser from '@ebag/rb-question-parser'
import { useComment } from '@/stores/comment'
import { ref, computed, watch, reactive } from 'vue'
import { transformImg, getToken, uploadImg } from '../utils'
import { useAuthStore } from '@/stores/auth-store'
import { getOssToken } from '@/apis/common/oss.js'
import { getRecommendVideo } from '@/apis/comment/index'
const originQuestionList = ref([])
const userStore = useAuthStore()
const commentStore = useComment()
const questionRef = ref(null)

const props = defineProps({
  index: {
    type: Number,
    default: 0
  },
  content: {
    type: Object,
    default: () => {}
  },
  isShowAnswer: {
    type: Boolean,
    default: false
  },
  isChecked: {
    type: Boolean,
    default: false
  }
})
const rbqOption = ref({
  host: {
    resourceHost: 'https://contres.readboy.com/' // 静态资源(图片、音频等)服务器域名
  },
  displayAnswer: false, // 是否显示题目答案，显示答案时不能作答
  interactive: false, // 是否可作答
  readonly: true, // 可作答时是否只读（只显示之前的作答情况但不能改）
  // answerColor?: string; // 答案颜色，值为css颜色声明
  // enableContentFold?: boolean; // 是否启用题干折叠，默认不启用
  enableSolution: false, // 是否显示答案和解析，默认不显示
  fontSize: '16px'
})
const emits = defineEmits(['show-answer', 'checked', 'show-video'])
const videoUrl = reactive({
  url: '',
  poster: ''
})
const showAnswer = () => {
  emits('show-answer', !props.isShowAnswer)
}
const check = async () => {
  let file = null
  if (!props.isChecked) {
    file = await transformImg(questionRef.value)
  }
  emits('checked', {
    isChecked: !props.isChecked,
    questionImg: file
  })
}
const questionData = computed(() => {
  const detail = props.content
  const res = {
    typeDetail: detail?.type || detail?.category,
    data: detail
  }
  return res
})

const getParseRes = computed(() => {
  const res = QuestionParser.parse(questionData.value, rbqOption.value)
  return res
})

const getDifficulty = computed(() => {
  const content = props.content
  return DIFFICULTY_ENUM[content?.difficulty] || ''
})

const getType = computed(() => {
  const content = props.content
  return content.question_type || ''
})

const getAnswer = computed(() => {
  const answer = getParseRes.value.answer
  const res = answer.map(item => letters[item])
  return res.join('')
})

const showVideo = () => {
  console.log('video', videoUrl)
  emits('show-video', videoUrl)
}

watch(
  () => originQuestionList.value,
  () => {
    if (originQuestionList.value.length > 0) {
      const current = originQuestionList.value[0]
      videoUrl.url = current.url
      videoUrl.poster = `${videoUrl.url}?vframe/jpg/offset/1`
    } else {
      videoUrl.url = ''
      videoUrl.poster = ''
    }
  },
  {
    deep: true
  }
)

// 根据图片获取原题视频
const getVideo = async url => {
  const params = {
    url: url,
    question_id: props.content.id,
    user: {
      id: +userStore.userInfo.userId,
      name: userStore.userInfo.userName
    }
  }
  const { data } = await getRecommendVideo(params)
  originQuestionList.value = data || []
}

watch(
  () => props.isShowAnswer,
  async val => {
    videoUrl.url = ''
    videoUrl.poster = ''
    if (val && questionRef.value) {
      const file = await transformImg(questionRef.value)
      await getToken()
      const result = await uploadImg(file)
      if (result.url) getVideo(result.url)
    }
  }
)
</script>
<style lang="less" scoped>
.similar-question-item {
  padding: 24px;
  border-radius: 8px;
  border: 1px solid rgba(173, 200, 255, 0.7);
  margin-bottom: 24px;

  .btn-primary {
    border: 0;
    padding: 0 16px;
    min-width: 80px;
    height: 40px;
    border-radius: 8px;
    background-color: @theme-color;
    font-size: @base-size;
    color: #fff;
    cursor: pointer;

    &:not(:disabled):hover {
      background-color: @theme-color--hover;
    }

    &.disabled,
    &:disabled {
      opacity: 0.4;
      cursor: not-allowed;
    }
  }

  .btn-text {
    border: 0;
    background-color: transparent;
    font-size: @base-size;
    color: @minor-font-color;
    cursor: pointer;

    &:not(:disabled):hover {
      color: @theme-color--hover;
    }

    &:not(:disabled):active {
      color: @theme-color--active;
    }

    &.disabled,
    &:disabled {
      opacity: 0.5;
      cursor: not-allowed;
    }
  }

  .title {
    display: flex;
    .left {
      flex: 1;
      display: flex;
      gap: 12px;

      span {
        background: #f3f5f9;
        border-radius: 8px;
        display: inline-block;
        padding: 6px 8px;
        color: rgba(4, 11, 26, 0.3);
      }
      .num {
        margin-right: 12px;
      }
    }

    .right {
      display: flex;
      justify-content: flex-end;
      width: 200px;

      label {
        background: #f3f5f9;
        border-radius: 8px;
        display: inline-block;
        padding: 6px 8px;
        color: rgba(51, 202, 164, 1);
      }
    }
  }

  :deep(.rb-question) {
    padding-top: 32px;
    .content-container {
      background: inherit;
      padding: 0;
    }

    .option-list-choice {
      padding: 0;
    }

    .rbq-content {
      overflow: hidden;
      p {
        margin-top: 0;
      }
    }
  }

  .footer {
    display: flex;
    justify-content: flex-end;
    gap: @gap;

    .answer-btn {
      display: inline-flex;
      align-items: center;
      .icon {
        width: 20px;
        height: 20px;
        display: inline-block;
        background: url('@/assets/images/comment/show-answer.png') no-repeat
          center/cover;
      }

      &.active,
      &:hover {
        color: rgba(51, 202, 164, 1);
        .icon {
          width: 20px;
          height: 20px;
          display: inline-block;
          background: url('@/assets/images/comment/show-answer-press.png')
            no-repeat center/cover;
        }
      }
    }

    .btn-primary {
      background: rgba(51, 202, 164, 1);
    }

    .select-btn {
      &.active {
        background: #fff;
        border: rgba(51, 202, 164, 1) 1px solid;
        color: rgba(51, 202, 164, 1);
      }

      &:hover {
        background: rgba(51, 202, 164, 1);
        color: #fff;
      }
    }
  }

  .answer {
    display: flex;
    flex-direction: column;
    gap: 24px;
    li {
      list-style-type: none;
      display: flex;
      label {
        max-width: 100px;
        font-weight: 700;
      }

      .detail {
        flex: 1;
      }
    }
  }

  .key-point-label,
  .explain-label {
    display: inline-block;
    padding-top: 6px;
  }
  .key-point-list {
    display: flex;
    gap: 10px;

    .key-point {
      display: inline-block;
      border-radius: 8px;
      padding: 6px 8px;
      background: rgba(230, 248, 244, 0.8);
      color: rgba(0, 189, 141, 1);
      width: fit-content;
    }
  }

  .explain {
    padding: 6px 8px;
    border-radius: 8px;
    background: rgba(230, 248, 244, 0.8);
    color: #33caa4;
    display: inline-flex;
    align-items: center;
    gap: 8px;
    justify-content: center;
    border: none;
    cursor: pointer;

    label {
      cursor: pointer;
      width: 20px;
      height: 20px;
      display: inline-block;
      background: url('@/assets/images/comment/video.png') no-repeat
        center/cover;
    }

    &:hover {
      background: #33caa4;
      color: #fff;

      label {
        background: url('@/assets/images/comment/video-active.png') no-repeat
          center/cover;
      }
    }
  }
}
</style>
